package com.taptech.doufu.ui.adapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.UserDetailActivity;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.NewOthersPersonalActivity;
import com.taptech.doufu.bean.UserBean;
import com.taptech.doufu.bean.CommentDataBean;
import com.taptech.doufu.bean.ReplyDataBean;
import com.taptech.doufu.services.CommentService;
import com.taptech.doufu.util.CommentUtil;
import com.taptech.doufu.util.CommentUtil.InputDialogHandCallback;
import com.taptech.doufu.listener.Replyable;
import com.taptech.doufu.ui.view.ReplyList;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.util.at.AtUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.NetworkImageView;
import com.taptech.doufu.ui.view.PullToRefreshListView;

import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NovelReplyAdapter extends BaseListAdapter
{

    public static final int TYPE_COMMENT = 1;
    public static final int TYPE_REPLY = 2;
    public static final int space = ScreenUtil2.dip2px(13);

    public Activity activity;
    private boolean showAll;
    private UserBean publishMan = null;
    private UserBean replyMan = null;
    private CommentDataBean parentComment;
    private ReplyList selfList;
    private boolean isTitle;
    private String mAuthorId;

    private int testLog = 0;
    private CommentDataBean forMoreReply;
    private PullToRefreshListView moreReplyList;

    public NovelReplyAdapter(Activity activity)
    {
        this.activity = activity;
    }

    public void setVisibilityTitle(boolean isTitle)
    {
        this.isTitle = isTitle;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        //TTLog.d("tag" , "the reply log count is=======" + (testLog++));
        ViewHolder holder;
        if (convertView == null)
        {
            holder = new ViewHolder();
            convertView = activity.getLayoutInflater().inflate(R.layout.novel_component_reply_adapter, null);
            holder.backLayout = (RelativeLayout) convertView.findViewById(R.id.backgroud_layout);
            holder.icon = (NetworkImageView) convertView.findViewById(R.id.novel_comment_user_icon);
            holder.userMedal = (ImageView) convertView.findViewById(R.id.novel_comment_user_medal);

            holder.userName = (TextView) convertView.findViewById(R.id.novel_comment_user_name);
            holder.content = (TextView) convertView.findViewById(R.id.novel_comment_contents);
            holder.replyList = (ReplyList) convertView.findViewById(R.id.novel_reply_list);
            holder.lien = convertView.findViewById(R.id.novel_comment_reply_lien);
            holder.publishTime = (TextView) convertView.findViewById(R.id.novel_comment_publishTime);

            holder.contentGroup = convertView.findViewById(R.id.novel_comment_content_view_group);
            holder.novelTitleName = (TextView) convertView.findViewById(R.id.novel_comment_article_name);
            holder.novelTitleLayout = (LinearLayout) convertView.findViewById(R.id.novel_comment_article_title_layout);
            holder.isAuthor = (TextView) convertView.findViewById(R.id.novel_comment_name_is_owner);
            holder.watch_more_reply_tv = (TextView) convertView.findViewById(R.id.watch_more_reply_tv);
            convertView.setTag(holder);
        } else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        initData(convertView, holder, position);

        return convertView;
    }

    private void initData(View convertView, ViewHolder viewHolder, final int position)
    {
        try
        {
            publishMan = null;
            replyMan = null;
            convertView.setClickable(true);
            String content = "";
            final ViewHolder holder = viewHolder;
            holder.icon.setImageResource(R.drawable.default_user_portrait);
            holder.icon.setRound(true);
            holder.userName.setText("");
            holder.content.setText("");
            holder.lien.setVisibility(View.VISIBLE);
            holder.replyList.setVisibility(View.GONE);
            // holder.contentGroup.setPadding(0, 0, space, 0);

            StringBuilder sb = new StringBuilder();
            int publisNameLength = 0;
            int replyNameLength = 0;
            CommentDataBean comment = null;
            ReplyDataBean reply = null;

            if (getDataSource().get(position) instanceof CommentDataBean)
            {
                comment = (CommentDataBean) getDataSource().get(position);
                publishMan = comment.getUser();
                if (publishMan == null)
                    return;
                holder.icon.setOnClickListener(new OnClickListener()
                {

                    @Override
                    public void onClick(View v)
                    {
                        String userId = ((CommentDataBean) getDataSource().get(position)).getUser().getUserId();
                        if (!userId.equals(AccountService.getInstance().getUserUid())) {
                            UserDetailActivity.Companion.startActivity(v.getContext(),userId);
                        }
                    }
                });
                publisNameLength = publishMan.getName().length();
                content = comment.getComment_content();
                holder.publishTime.setText(DiaobaoUtil.seconds2TimeString(Long.parseLong(comment.getComment_time())));

                sb.append(publishMan.getName());
                NovelReplyAdapter adapter = new NovelReplyAdapter(activity);
                adapter.setAuthorId(this.mAuthorId);
                adapter.parentComment = comment;
                adapter.selfList = holder.replyList;
                if (forMoreReply == null && moreReplyList == null && comment.getReplies().size() > 2)
                {
                    adapter.setDataSource(comment.getReplies().subList(0, 2));
                } else
                {
                    adapter.setDataSource(comment.getReplies());
                }
                holder.replyList.setAdapter(adapter);

                if (comment.getReplies() != null && comment.getReplies().size() > 0)
                {
                    holder.replyList.setVisibility(View.VISIBLE);
                    //UIUtil.setListViewHeightBasedOnChildren(holder.replyList);
                } else
                {
                    holder.lien.setVisibility(View.INVISIBLE);
                }

                // 回复评论
                holder.backLayout.setOnClickListener(new OnClickListener()
                {

                    @Override
                    public void onClick(View v)
                    {
                        // TODO Auto-generated method stub
                        if (!AccountService.getInstance().isLogin())
                        {
                            UIUtil.toastMessage(activity, activity.getResources().getString(R.string.name_login_tips));
                            return;
                        }
                        CommentDataBean comment = (CommentDataBean) getDataSource().get(position);

                        if (activity instanceof Replyable)
                        {

                            TTLog.d("tag", "reply ======= 无法被回复");
                            ((Replyable) activity).reply(comment, comment.getUser(), "");
                        } else
                        {
                            TTLog.d("tag", "reply ======= 可以被回复");
                            CommentUtil.showReplyDialog(activity, comment.getUser(), new ReplyCallback(comment, comment.getUser(), "", holder.replyList));
                        }
                    }
                });
                holder.content.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {
                        if (!AccountService.getInstance().isLogin())
                        {
                            UIUtil.toastMessage(activity, activity.getResources().getString(R.string.name_login_tips));
                            return;
                        }
                        CommentDataBean comment = (CommentDataBean) getDataSource().get(position);

                        if (activity instanceof Replyable)
                        {
                            ((Replyable) activity).reply(comment, comment.getUser(), "");
                        } else
                        {
                            CommentUtil.showReplyDialog(activity, comment.getUser(), new ReplyCallback(comment, comment.getUser(), "", holder.replyList));
                        }
                    }
                });

                // 显示小说评论在哪一章节
                if (isTitle && comment.getArticle() != null)
                {
                    holder.novelTitleLayout.setVisibility(View.VISIBLE);
                    if (comment.getArticle() != null && comment.getArticle().getOrigin_title() != null)
                    {
                        holder.novelTitleName.setText(comment.getArticle().getOrigin_title());
                    }
                } else
                {
                    holder.novelTitleLayout.setVisibility(View.GONE);
                }
                int replyNum = DiaobaoUtil.String2Int(((CommentDataBean) getDataSource().get(position)).getReply_times());
                String articleNub = (replyNum) > 2 ? "查看更多" + (replyNum - 2) + "条回复" : "";
                holder.watch_more_reply_tv.setText(articleNub);
                holder.watch_more_reply_tv.setVisibility((replyNum) > 2 ? View.VISIBLE : View.GONE);
            } else
            {
                reply = (ReplyDataBean) getDataSource().get(position);
                content = reply.getContent();
                publishMan = reply.getUser();
                if (publishMan == null)
                    return;
                holder.icon.setOnClickListener(new OnClickListener()
                {

                    @Override
                    public void onClick(View v)
                    {
                        String userId = ((ReplyDataBean) getDataSource().get(position)).getUser().getUserId();
                        if (!userId.equals(AccountService.getInstance().getUserUid())) {
                            UserDetailActivity.Companion.startActivity(v.getContext(),userId);
                        }
                    }
                });

                replyMan = reply.getTo_user();
                if (publishMan == null)
                {
                    holder.lien.setVisibility(View.INVISIBLE);
                    return;
                }
                // holder.contentGroup.setPadding(0, 0, 0, 0);
                holder.publishTime.setText(DiaobaoUtil.seconds2TimeString(Long.parseLong(reply.getAdd_time())));
                publisNameLength = publishMan.getName().length();

                sb.append(publishMan.getName());
                String toUserName = "";
                if (replyMan != null)
                {
                    toUserName = replyMan.getName();
                    if (!publishMan.getName().equals(toUserName))
                    {
                        sb.append("回复" + toUserName + ":");
                    }
                }

                if (position == (getCount() - 1))
                    holder.lien.setVisibility(View.INVISIBLE);
                else
                    holder.lien.setVisibility(View.GONE);

                convertView.findViewById(R.id.novel_comment_contents).setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {
                        if (!AccountService.getInstance().isLogin())
                        {
                            UIUtil.toastMessage(activity, activity.getResources().getString(R.string.name_login_tips));
                            return;
                        }

                        TTLog.d("tag", "reply========点击回复事件");
                        UserBean user = null;
                        String replyId = "";
                        if (getDataSource().get(position) instanceof ReplyDataBean)
                        {
                            user = ((ReplyDataBean) getDataSource().get(position)).getUser();
                            replyId = ((ReplyDataBean) getDataSource().get(position)).getReply_id();

                        } else
                        {
                            user = ((CommentDataBean) getDataSource().get(position)).getUser();
                        }

                        if (activity instanceof Replyable)
                        {
                            ((Replyable) activity).reply(parentComment, user, replyId);
                        } else
                        {

                            CommentUtil.showReplyDialog(activity, user, new ReplyCallback(parentComment, user, "", selfList));
                        }
                    }
                });
                //点击回复评论的回复
                convertView.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (!AccountService.getInstance().isLogin())
                        {
                            UIUtil.toastMessage(activity, activity.getResources().getString(R.string.name_login_tips));
                            return;
                        }

                        TTLog.d("tag", "reply========点击回复事件2");
                        UserBean user = null;
                        String replyId = "";
                        if (getDataSource().get(position) instanceof ReplyDataBean)
                        {
                            user = ((ReplyDataBean) getDataSource().get(position)).getUser();
                            replyId = ((ReplyDataBean) getDataSource().get(position)).getReply_id();

                        } else
                        {
                            user = ((CommentDataBean) getDataSource().get(position)).getUser();
                        }

                        if (parentComment == null && forMoreReply != null)
                        {
                            parentComment = forMoreReply;
                        }
                        if (activity instanceof Replyable)
                        {
                            ((Replyable) activity).reply(parentComment, user, replyId);
                        } else
                        {
                            CommentUtil.showReplyDialog(activity, user, new ReplyCallback(parentComment, user, replyId, selfList));
                        }
                    }
                });
            }

            SpannableStringBuilder tipInfotyle = new SpannableStringBuilder(sb);
            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#9e9e9e"));

            tipInfotyle.setSpan(new PersonalClickable(publishMan, holder.icon.getDrawingCache()), 0, publisNameLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tipInfotyle.setSpan(span, 0, publisNameLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            if (replyMan != null)
            {
                if (!publishMan.getName().equals(replyMan.getName()))
                {
                    replyNameLength = replyMan.getName().length();
                    // 回复颜色
                    span = new ForegroundColorSpan(convertView.getContext().getResources().getColor(R.color.top_title_red_color));
                    tipInfotyle.setSpan(span, publisNameLength, publisNameLength + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span = new ForegroundColorSpan(Color.parseColor("#9e9e9e"));
                    tipInfotyle.setSpan(new PersonalClickable(replyMan, holder.icon.getDrawingCache()), publisNameLength + 2, publisNameLength + 2 + replyNameLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tipInfotyle.setSpan(span, publisNameLength + 2, publisNameLength + 2 + replyNameLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tipInfotyle.setSpan(new ReplyClickable(replyMan, selfList), publisNameLength + 2 + replyNameLength, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            RelativeSizeSpan relaSize = new RelativeSizeSpan(1.2f);
            tipInfotyle.setSpan(relaSize, 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            holder.icon.setURL(publishMan.getIcon());
            DiaobaoUtil.setMedalImgView(publishMan.getMedal(), holder.userMedal);
            // 是否为作者本人
            Log.d("tag", "发布者ID为" + publishMan.getUserId());
            Log.d("tag", "作者ID为" + mAuthorId);
            if (publishMan.getUserId().equals(mAuthorId))
            {
                holder.isAuthor.setVisibility(View.VISIBLE);
            } else
            {
                holder.isAuthor.setVisibility(View.GONE);
            }
            holder.userName.setText(tipInfotyle);
            holder.userName.setMovementMethod(LinkMovementMethod.getInstance());
            //holder.content.setText(content);
            new AtUtil(holder.content, content, Constant.AT_CLICK);
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public void setDataForMoreReply(CommentDataBean dataForMoreReply, PullToRefreshListView list)
    {
        this.forMoreReply = dataForMoreReply;
        this.moreReplyList = list;
    }

    class PersonalClickable extends ClickableSpan
    {
        private UserBean person;
        private Bitmap userPortrait;

        public PersonalClickable(UserBean person, Bitmap userPortrait)
        {
            this.person = person;
            this.userPortrait = userPortrait;
        }

        @Override
        public void onClick(View widget)
        {
            if (!publishMan.getUserId().equals(AccountService.getInstance().getUserUid())) {
                UserDetailActivity.Companion.startActivity(widget.getContext(),person.getUserId());
            }
        }

        @Override
        public void updateDrawState(TextPaint ds)
        {
            ds.setUnderlineText(false);
        }
    }

    class ReplyClickable extends ClickableSpan
    {

        private UserBean data;
        ReplyList list;

        public ReplyClickable(UserBean data, ReplyList list)
        {
            this.data = data;
            this.list = list;
        }

        @Override
        public void onClick(View widget)
        {
            CommentUtil.showReplyDialog(activity, data, new ReplyCallback(parentComment, data, "", list));
        }

        @Override
        public void updateDrawState(TextPaint ds)
        {
            ds.setUnderlineText(false);
        }

    }

    class ReplyCallback implements InputDialogHandCallback
    {

        CommentDataBean comment;
        UserBean replyUser;
        ReplyList list;
        String toReplyId;

        public ReplyCallback(CommentDataBean comment, UserBean reply, String toReplyId, ReplyList list)
        {
            this.comment = comment;
            this.replyUser = reply;
            this.list = list;

            this.toReplyId = toReplyId;
        }

        @Override
        public void handleComplete(String message)
        {
            if (comment == null && forMoreReply != null)
            {
                comment = forMoreReply;
            }
            try
            {
                String userId = comment.getUser().getUserId();
                if (replyUser != null)
                    userId = replyUser.getUserId();
                CommentService.getInstance().replyComment(comment.getArticle_id(), comment.getComment_id(), userId, toReplyId, message, activity, new HttpResponseListener()
                {
                    @Override
                    public void handleResponse(int handleType, HttpResponseObject response)
                    {

                        if (response.getStatus() == Constant.STATUS_SUCCESS)
                        {

                            List<ReplyDataBean> replys = comment.getReplies();
                            if (replys == null)
                            {
                                replys = new LinkedList<ReplyDataBean>();

                            }
                            ReplyDataBean replyData = new ReplyDataBean();
                            replyData.setJson((JSONObject) response.getData());
                            replyData.getUser().setName(AccountService.getInstance().getBaseAccount().getNickname());
                            replys.add(replyData);
                            comment.setReply_times("" + replys.size());
                            comment.setReplies(replys);
                            if (list != null)
                            {
                                NovelReplyAdapter adapter = (NovelReplyAdapter) list.getAdapter();
                                adapter.setDataSource(replys);
                            } else
                            {
                                setDataSource(replys);
                            }
                            UIUtil.toastMessage(activity, "回复成“攻”");
                            InputMethodManager im = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                            im.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        } else
                        {
                            UIUtil.toastMessage(activity, "回复失败");
                        }
                    }
                });
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }

    public class ViewHolder
    {
        TextView content, userName, publishTime, novelTitleName;
        ReplyList replyList;
        NetworkImageView icon;
        ImageView userMedal;
        View lien, contentGroup;
        LinearLayout novelTitleLayout;
        TextView isAuthor;
        RelativeLayout backLayout;
        TextView watch_more_reply_tv;
    }

    public boolean isShowAll()
    {
        return showAll;
    }

    public void setShowAll(boolean showAll)
    {
        this.showAll = showAll;
    }

    public String getAuthorId()
    {
        return mAuthorId;
    }

    public void setAuthorId(String mAuthorId)
    {
        this.mAuthorId = mAuthorId;
    }

}